# coding: utf-8

from datetime import date

from sqlalchemy.orm import validates

from exts import db


class AccBasic(db.Model):
    """
    资金账户基本信息
    """
    __tablename__ = "acc_basic"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False, comment="ID")
    acc_id = db.Column(db.CHAR(6), nullable=False, unique=True, index=True, comment="账户ID")
    name = db.Column(db.String(50), nullable=False, comment="账户名称")
    type_ = db.Column(db.CHAR(10), nullable=False, comment="账户类型")
    subtype = db.Column(db.CHAR(5), comment="子类型")
    owner = db.Column(db.String(12), nullable=False, comment="持有人")
    balance = db.Column(db.DECIMAL(10, 2), nullable=False, default=0, comment="余额")

    set_type_ = {"投资"}
    set_subtype = {"基金", "股票"}

    @property
    def dict_(self):
        _dict = self.__dict__
        for key in _dict.keys():
            if isinstance(_dict[key], date):
                _dict[key] = str(_dict[key])
        if _dict.get("_sa_instance_state"):
            _dict.pop("_sa_instance_state")
        return _dict

    @validates("type_")
    def validate_type_(self, key, ttype_):
        if ttype_ not in self.set_type_:
            raise Exception("账户类型只能是投资")
        return ttype_

    @validates("subtype")
    def validate_subtype(self, key, subtype):
        if subtype not in self.set_subtype:
            raise Exception("子类型只能是股票或基金")
        return subtype


class AccTrade(db.Model):
    """
    资金账户基本信息
    """
    __tablename__ = "acc_trade"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, nullable=False, comment="ID")
    trade_id = db.Column(db.CHAR(10), nullable=False, comment="交易ID")
    acc_id = db.Column(db.CHAR(6), index=True, nullable=False, comment="账户ID")
    post_date = db.Column(db.Date, nullable=False, comment="过账日期")
    dc = db.Column(db.CHAR(1), nullable=False, comment="借贷")
    type_ = db.Column(db.CHAR(10), nullable=False, comment="交易类型")
    fund_trade_id = db.Column(db.CHAR(10), comment="基金交易ID")
    amount = db.Column(db.DECIMAL(10, 2), nullable=False, comment="交易金额")
    balance = db.Column(db.DECIMAL(10, 2), nullable=False, comment="余额")

    set_type_ = {"转入", "转出", "投资", "回收", "投资", "亏损"}
    dict_dc = {"D": "借方", "C": "贷方"}

    @property
    def dict_(self):
        _dict = self.__dict__
        for key in _dict.keys():
            if isinstance(_dict[key], date):
                _dict[key] = str(_dict[key])
        if _dict.get("_sa_instance_state"):
            _dict.pop("_sa_instance_state")
        return _dict

    @validates("type_")
    def validate_type_(self, key, ttype_):
        if ttype_ not in self.set_type_:
            raise Exception("交易类型有误")
        return ttype_

    @validates("dc")
    def validate_type_(self, key, dc):
        if dc not in self.dict_dc.keys():
            raise Exception("借贷只允许D、C")
        return dc
